package cn.edu.cuc.yjsy.admin.dialogs;

import java.io.IOException;
import org.eclipse.jface.wizard.Wizard;

import cn.edu.cuc.yjsy.admin.connection.TargetConnection;
import cn.edu.cuc.yjsy.admin.util.ILogger;
import cn.edu.cuc.yjsy.admin.util.LoggerAdvisor;
import cn.edu.cuc.yjsy.admin.util.MessageHelper;
import cn.edu.cuc.yjsy.database.Database;
import cn.edu.cuc.yjsy.database.Table;

public class ConfigurationWizard extends Wizard {
	
	private ILogger logger = new LoggerAdvisor(ConfigurationWizard.class);
	private DatabaseLocationPage locationPage;
	protected boolean locationCompleted = false;
	
	public ConfigurationWizard(){
		setWindowTitle(MessageHelper.WIZARD_TITLE);
	}

	public void addPages() {
		locationPage = new DatabaseLocationPage("location", 
				MessageHelper.WIZARD_LOCATIONPAGE_TITLE, null);
		addPage(locationPage);
	}
	
	/**
	 * @override
	 */
	public boolean canFinish() {
		
		return locationCompleted;
	}
	
	public boolean performFinish() {
		boolean rt = false;
		TargetConnection connection = TargetConnection.getInstance();
		Database db = connection.getDatabase();
		String oldUrl = db.getUrl();
		Table t = (Table)db.getTable().get(0);
		String oldTable = t.getTableName();
		db.setUrl(locationPage.getDatabaseUrl());
		t.setTableName(locationPage.getTableName());
		
		try {
			connection.saveConfiguration();
			rt = true;
		} catch (IOException e) {
			db.setUrl(oldUrl);
			t.setTableName(oldTable);
			logger.error("Can't save the database configuration.");
		}
		return rt;
	}

}
